#pragma once
#include <iostream>
#include <jsoncpp/json/json.h>
#include <string>
#include <sstream>
#include <memory>

namespace cloud
{
class JsonUtil
{
public:
    // 将root的序列化结果保存在str中
    static bool serialize(const Json::Value& root, std::string* str)
    {
        Json::StreamWriterBuilder swb;
        std::unique_ptr<Json::StreamWriter> ps(swb.newStreamWriter());
        std::stringstream ss;

        if (ps->write(root, &ss) != 0) {
            std:: cerr << "write error!\nstatic bool serialize(const Json::Value& root, std::string* str)\n";
            return false;
        } 
        
        *str = ss.str();
        return true;
    }

    // 将str的序列化结果保存在root中
    static bool unserialize(const std::string& str, Json::Value* root)
    {
        Json::CharReaderBuilder crb;
        std::unique_ptr<Json::CharReader> ps(crb.newCharReader());
        
        std::string errs;
        if (ps->parse(str.c_str(), str.c_str() + str.size(), root, &errs) == false) {
            std::cerr << "parse error! why: " << str  << "\nstatic bool unserialize(const std::string& str, Json::Value* root)\n";
            return false;
        }

        return true;
    }
};
}